package ru.amse.tsyganov.jumleditor.view.activepoints;

import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.graphicaleditor.Coordinates;
import ru.amse.tsyganov.jumleditor.view.lines.Line;
import ru.amse.tsyganov.jumleditor.view.preferences.Colors;
import ru.amse.tsyganov.jumleditor.view.preferences.Cursors;

public class LineEditingActivePoint extends ActivePoint {
	
	private final boolean isHorizontal;
	
	private final Line line;
	
	public LineEditingActivePoint(Line line) {
		
		this.isHorizontal = line.getY1() == line.getY2();
		this.line = line;
	}

	@Override
	public Command createCommandForAction() {
		if (isHorizontal) {
			line.setY1(getTemporaryActivePointY());
			line.setY2(getTemporaryActivePointY());
		} else {
			line.setX1(getTemporaryActivePointX());
			line.setX2(getTemporaryActivePointX());
		}
		return null;
	}

	@Override
	public void paintTempResult(GC gc, Coordinates coordinates) {
		gc.setForeground(Colors.getGrayColor());
		int minX = Math.min(getTemporaryActivePointX(), 
				Math.min(getLine().getX1(), getLine().getX2()));
		int minY = Math.min(getTemporaryActivePointY(), 
				Math.min(getLine().getY1(), getLine().getY2()));
		int maxX = Math.max(getTemporaryActivePointX(), 
				Math.max(getLine().getX1(), getLine().getX2()));
		int maxY = Math.max(getTemporaryActivePointY(), 
				Math.max(getLine().getY1(), getLine().getY2()));
		
		gc.drawRectangle(
				coordinates.fromModelXToScreenX(minX), 
				coordinates.fromModelYToScreenY(minY), 
				maxX - minX, maxY - minY);
	}
	
	@Override
	public final Cursor getCursor() {
		return isHorizontal ? Cursors.getCursorSizeNS() : 
			Cursors.getCursorSizeWE();
	}

	@Override
	public int getCurrentActivePointX() {
		return (line.getX1() + line.getX2()) / 2;
	}

	@Override
	public int getCurrentActivePointY() {
		return (line.getY1() + line.getY2()) / 2;
	}

	public Line getLine() {
		return line;
	}

}
